package com.zhz.mall.common.util;

import cn.hutool.core.exceptions.ExceptionUtil;
import lombok.Lombok;

import java.util.Objects;
import java.util.concurrent.Callable;

/**
 * ExceptionUtils
 * <p>
 * 异常工具类
 *
 * @author zhouhengzhe
 */
public abstract class ExceptionUtils extends ExceptionUtil {


    /**
     * 获取异常信息，当异常信息为空时，返回异常名
     */
    public static String getMessage(Throwable cause) {
        return Objects.nonNull(cause.getMessage()) ? cause.getMessage() : cause.getClass().getName();
    }


    /**
     * 当目标异常为指定异常类型，且父异常不为空时，返回父异常，否则返回原异常
     */
    public static Throwable unwrapSuperCause(Throwable cause, Class<? extends Throwable> targetType) {
        if (targetType.isInstance(cause) && Objects.nonNull(cause.getCause())) {
            return cause.getCause();
        }
        return cause;
    }


    /**
     * 直接抛出异常
     */
    public static void sneakyThrow(Throwable cause) {
        throw Lombok.sneakyThrow(cause);
    }


    public static void unSupported() {
        throw new UnsupportedOperationException();
    }


    public static void unSupported(String msg) {
        throw new UnsupportedOperationException(msg);
    }


    /**
     * 忽略掉异常信息
     */
    public static void ignore(Runnable runnable) {
        ignore(() -> {
            runnable.run();
            return null;
        });
    }


    /**
     * 忽略掉异常信息
     */
    public static <T> T ignore(Callable<T> callable) {
        try {
            return callable.call();
        } catch (Throwable ignored) {}
        return null;
    }
}
